<?php

namespace App\Http\Exports;

use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use App\Model\Base;

class QueryExportGoodsSeilRank implements FromArray,WithHeadings,WithMapping
{

    use Exportable;

    public function __construct($param)
    {
        $this->param = $param;
    }

    public function array():array
    {
        $param = $this->param;

        $db = DB::table('user_order_detailed as uod')
            ->select(DB::raw( 'DISTINCT gm.goods_name,gm.goods_id,cm.category_name,cm.category_id'))
            ->leftJoin('goods_master as gm', 'gm.goods_id', '=', 'uod.goods_id')
            ->leftJoin('goods_model as gmm', 'gm.goods_id',  DB::raw('gmm.goods_id and gmm.goods_model_id = uod.model_id'))
            ->leftJoin('category_master as cm', 'cm.category_id', '=', 'gm.category_id');

        if (!empty($getParam['star_date']) && !empty($getParam['end_date'])) {
            $list = $db->whereBetween('uod.create_time', [$getParam['star_date'], $getParam['end_date']])->get()->map(function ($value) {
                return (array)$value;
            })->toArray();
        } else {
            $list = $db->get()->map(function ($value) {
                return (array)$value;
            })->toArray();
        }

        $linData = [];
        foreach ($list as $key => $value) {
            $goods = DB::table('user_order_detailed')
                ->select(DB::raw('sum(goods_num) as goods_num,sum(goods_price) as goods_price'))
                ->where('goods_id', '=', $value['goods_id'])
                ->first();
            $value['goods_num'] = $goods->goods_num;
            $value['goods_price'] = $goods->goods_price;

            $linData[] = $value;
        }

        return $linData;


    }

    public function headings(): array
    {
        return [
          'カテゴリー',
          '商品名',
          '数量',
          '価格',
        ];
    }

    public function map($invoice):array
    {
        return [
            $invoice['category_name'],
            $invoice['goods_name'],
            $invoice['goods_num'],
            $invoice['goods_price'],
        ];
    }

}
